package com.zhsj.OkeHomeConsumption.ui.activity.bussiness;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hjq.base.BaseDialog;
import com.hjq.dialog.MenuDialog;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.orhanobut.hawk.Hawk;
import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.adapter.GridViewAddImgesAdpter;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.MyActivity;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.empty.UpLoadImgBean;
import com.zhsj.OkeHomeConsumption.helper.GlideEngine;
import com.zhsj.OkeHomeConsumption.ui.activity.bussiness.mvp.BusinessmaintainPresenter;
import com.zhsj.OkeHomeConsumption.ui.activity.bussiness.mvp.BusinessmaintainUIInterFace;
import com.zhsj.OkeHomeConsumption.ui.activity.wallet.ClearEditText;
import com.zhsj.OkeHomeConsumption.utils.UpLoadGridView;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * author : Xingdx
 * <p>
 * time   : 2018/10/18
 * desc   : 店铺维护
 *
 */
public final class BusinessmaintainActivity extends MyActivity implements BusinessmaintainUIInterFace {


    @BindView(R.id.selet_phone)
    ClearEditText seletPhone;
    @BindView(R.id.selet_timer)
    ClearEditText seletTimer;
    @BindView(R.id.selet_fuwu)
    ClearEditText seletFuwu;

    @BindView(R.id.logogradle)
    UpLoadGridView logogradle;
    @BindView(R.id.btn_test_login)
    Button btnTestLogin;
    @BindView(R.id.end_timer)
    ClearEditText endTimer;
    private GridViewAddImgesAdpter logogradle_gridViewAddImgesAdpter;
    private List<UpLoadImgBean> logogradle_imageServiceList;

    @BindView(R.id.dianpubeijingtu)
    UpLoadGridView dianpubeijingtu;
    private GridViewAddImgesAdpter dianpubeijingtu_gridViewAddImgesAdpter;
    private List<UpLoadImgBean> dianpubeijingtu_imageServiceList;

    @BindView(R.id.dianputu)
    UpLoadGridView dianputu;
    private GridViewAddImgesAdpter dianputu_gridViewAddImgesAdpter;
    private List<UpLoadImgBean> dianputu_imageServiceList;

    //门脸图 1  店内图2   营业执照3  许可证4 log5 背景6 店铺图7
    private int REQUEST_CODE_CHOOSE = -1;

    // 图片集合
    private List<File> datas_menlian = null;
    private List<UpLoadImgBean> imageServiceList = null;

    private BusinessmaintainPresenter minePersonPresenter;

    private FormalUserInfo userinfo;

    private int id = -1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_businessmaintain;
    }

    @Override
    protected int getTitleId() {
        return R.id.tb_copy_title;
    }

    @Override
    protected void initView() {
        datas_menlian = new ArrayList<>();
        imageServiceList = new ArrayList<>();
        dianputu_imageServiceList = new ArrayList<>();
        logogradle_imageServiceList = new ArrayList<>();
        dianpubeijingtu_imageServiceList = new ArrayList<>();
        userinfo = Hawk.get(Constants.SHARED_PERFERENCE_USERINFO);
        minePersonPresenter = new BusinessmaintainPresenter(getActivity(), this);
        minePersonPresenter.FindByUserIdGet(userinfo.getId());

        seletTimer.setEnabled(true);
        seletTimer.setInputType(InputType.TYPE_NULL);
        seletTimer.setFocusableInTouchMode(false);
        seletTimer.setFocusable(false);
        seletTimer.setCursorVisible(false);

        endTimer.setEnabled(true);
        endTimer.setInputType(InputType.TYPE_NULL);
        endTimer.setFocusableInTouchMode(false);
        endTimer.setFocusable(false);
        endTimer.setCursorVisible(false);
    }

    @Override
    protected void initData() {
        logogradle_gridViewAddImgesAdpter = new GridViewAddImgesAdpter(logogradle_imageServiceList, getActivity());
        logogradle_gridViewAddImgesAdpter.setMaxImages(2);
        logogradle.setAdapter(logogradle_gridViewAddImgesAdpter);
        logogradle.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                //店铺logo
                REQUEST_CODE_CHOOSE = 5;
                ShootingDialog(REQUEST_CODE_CHOOSE, 1);
            }
        });

        dianpubeijingtu_gridViewAddImgesAdpter = new GridViewAddImgesAdpter(dianpubeijingtu_imageServiceList, getActivity());
        dianpubeijingtu_gridViewAddImgesAdpter.setMaxImages(2);
        dianpubeijingtu.setAdapter(dianpubeijingtu_gridViewAddImgesAdpter);
        dianpubeijingtu.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                //店铺背景图
                REQUEST_CODE_CHOOSE = 6;
                ShootingDialog(REQUEST_CODE_CHOOSE, 1);
            }
        });

        dianputu_gridViewAddImgesAdpter = new GridViewAddImgesAdpter(dianputu_imageServiceList, getActivity());
        dianputu_gridViewAddImgesAdpter.setMaxImages(8);
        dianputu.setAdapter(dianputu_gridViewAddImgesAdpter);
        dianputu.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                //店铺图
                REQUEST_CODE_CHOOSE = 7;
                ShootingDialog(REQUEST_CODE_CHOOSE, 8);
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    private void ShootingDialog(final int code, final int max) {
        String[] arreaArr = getActivity().getResources().getStringArray(R.array.shooting_type);
        final List<String> shooting_type_list = Arrays.asList(arreaArr);
        new MenuDialog.Builder(this)
                .setCancel("取消") // 设置 null 表示不显示取消按钮
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setList(shooting_type_list)
                .setListener(new MenuDialog.OnListener() {

                    @Override
                    public void onSelected(Dialog dialog, int position, String text) {
                        switch (position) {
                            case 0:
                                Pictureselection(position, max);
                                break;
                            case 1:
                                Pictureselection(position, max);
                                break;
                        }
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        toast("取消了");
                    }
                })
                .setGravity(Gravity.BOTTOM)
                .setAnimStyle(BaseDialog.AnimStyle.BOTTOM)
                .show();
    }


    /**
     * 图片选择
     */
    private void Pictureselection(int code, int max) {
        if (code == 0) {
            EasyPhotos.createCamera(this)//参数说明：上下文
                    .setFileProviderAuthority("com.zhsj.OkeHomeConsumption.fileprovider")//参数说明：见下方`FileProvider的配置`
                    .start(101);
        } else {
            EasyPhotos.createAlbum(this, false, GlideEngine.getInstance())//参数说明：上下文，是否显示相机按钮，[配置Glide为图片加载引擎](https://github.com/HuanTanSheng/EasyPhotos/wiki/12-%E9%85%8D%E7%BD%AEImageEngine%EF%BC%8C%E6%94%AF%E6%8C%81%E6%89%80%E6%9C%89%E5%9B%BE%E7%89%87%E5%8A%A0%E8%BD%BD%E5%BA%93)
                    .setCount(max)//参数说明：最大可选数，默认1
                    .setPuzzleMenu(false)
                    .start(101);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 101 && resultCode == RESULT_OK) {
            //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
            ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);
            datas_menlian.clear();
            for (int i = 0; i < resultPhotos.size(); i++) {
                datas_menlian.add(uri2File(resultPhotos.get(i).path));
            }
            minePersonPresenter.UploadPost(datas_menlian);
        }

    }

    /**
     * user转换为file文件
     * 返回值为file类型
     *
     * @param uri
     * @return
     */
    private File uri2File(String uri) {
        File file = new File(uri);
        return file;
    }

    @Override
    public void FindByUserIdGet(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONObject jsonobj = jsonOBJ.optJSONObject("data");
                seletPhone.setText(jsonobj.optString("shopMobile"));
                String timestr = jsonobj.optString("workTime");
                if(!timestr.equals("")){
                   String strttimer= timestr.substring(0,4);
                    String enttimer= timestr.substring(timestr.indexOf("-"));
                    seletTimer.setText(strttimer);
                    endTimer.setText(enttimer.substring(1));
                }
                id = jsonobj.optInt("id");
                seletFuwu.setText(jsonobj.optString("shopService"));
                dianpubeijingtu_imageServiceList.add(new UpLoadImgBean(jsonobj.optString("shopBackImg")));
                logogradle_imageServiceList.add(new UpLoadImgBean(jsonobj.optString("shopLogo")));
                JSONArray jsonArray = jsonobj.optJSONArray("shopImgs");
                List<String> list  = new Gson().fromJson(jsonArray.toString(), new
                        TypeToken<ArrayList<String>>() {
                        }.getType());
                for(int i =0;i<list.size();i++){
                    dianputu_imageServiceList.add(new UpLoadImgBean(list.get(i)));
                }
                logogradle_gridViewAddImgesAdpter.notifyDataSetChanged(logogradle_imageServiceList);
                dianpubeijingtu_gridViewAddImgesAdpter.notifyDataSetChanged(dianpubeijingtu_imageServiceList);
                dianputu_gridViewAddImgesAdpter.notifyDataSetChanged(dianputu_imageServiceList);
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            log("商家--- 店铺维护");
        }
    }

    @Override
    public void UploadPost(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                JSONArray jsondata = jsonOBJ.optJSONArray("data");
                if (imageServiceList.size() != 0) {
                    imageServiceList.clear();
                }
                imageServiceList = new Gson().fromJson(jsondata.toString(), new
                        TypeToken<ArrayList<UpLoadImgBean>>() {
                        }.getType());
                if (imageServiceList != null && imageServiceList.size() > 0) {
                    switch (REQUEST_CODE_CHOOSE) {
                        case 5:
                            for (int i = 0; i < imageServiceList.size(); i++) {
                                logogradle_imageServiceList.add(imageServiceList.get(i));
                            }
                            logogradle_gridViewAddImgesAdpter.notifyDataSetChanged(logogradle_imageServiceList);
                            break;
                        case 6:
                            for (int i = 0; i < imageServiceList.size(); i++) {
                                dianpubeijingtu_imageServiceList.add(imageServiceList.get(i));
                            }
                            dianpubeijingtu_gridViewAddImgesAdpter.notifyDataSetChanged(dianpubeijingtu_imageServiceList);
                            break;
                        case 7:
                            for (int i = 0; i < imageServiceList.size(); i++) {
                                dianputu_imageServiceList.add(imageServiceList.get(i));
                            }
                            dianputu_gridViewAddImgesAdpter.notifyDataSetChanged(dianputu_imageServiceList);
                            break;
                    }
                    imageServiceList.clear();

                }
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            log("城市合伙人--- 多张图片上传");
        }
    }

    @Override
    public void Update(String context) {
        try {
            JSONTokener jsonT = new JSONTokener(context);
            JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
            String code = jsonOBJ.optString("code");
            String message = jsonOBJ.optString("message");
            if (code.equals("N000000")) {
                toast("维护成功");
                finish();
            } else if (code.equals(Constants.STATUSTOKENERROR)) {
                // token过期
                if (!message.equals("null")) {
                    toast(message);
                }
            } else {
                if (!message.equals("null")) {
                    toast(message);
                }
            }
        } catch (JSONException ex) {
            Log.e("Update", "店铺维护与详情");
        }
    }

    @OnClick({R.id.btn_test_login,R.id.selet_timer,R.id.end_timer})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.btn_test_login:
                //提交
                submit();
                break;
            case R.id.selet_timer:
                //开始时间
                TimerDialog(0);
                break;
            case R.id.end_timer:
                //开始时间
                TimerDialog(1);
                break;
        }

    }

    private void submit() {


        String shopphone = seletPhone.getText().toString();
        if (shopphone.equals("")) {
            toast("请输入商铺电话");
            return;
        }
        String shopService = seletFuwu.getText().toString();
        if (shopService.equals("")) {
            toast("请输入商铺服务");
            return;
        }


        String starttimer = seletTimer.getText().toString();
        if (starttimer.equals("")) {
            toast("请选择开始营业时间");
            return;
        }
        String endtimer = endTimer.getText().toString();
        if(endtimer.equals("")){
            toast("请选择结束营业时间");
            return;
        }
        if (logogradle_imageServiceList.size() == 0) {
            toast("请上传店铺LOGO");
            return;
        }
        if (dianpubeijingtu_imageServiceList.size() == 0) {
            toast("请上传店铺背景图");
            return;
        }
        if (dianputu_imageServiceList.size() == 0) {
            toast("请上传店铺图");
            return;
        }


        Gson gson = new Gson();
        Map<String, Object> mapjson = new HashMap<>();
        mapjson.put("id", id);
        mapjson.put("shopMobile", shopphone);//商铺电话
        mapjson.put("workTime", starttimer + "-" + endtimer);
        mapjson.put("shopService", shopService);

        mapjson.put("shopLogo", slipet(logogradle_imageServiceList.get(0).getPhotoPath().toString()));
        mapjson.put("shopBackImg", slipet(dianpubeijingtu_imageServiceList.get(0).getPhotoPath().toString()));
        List<String> list1 = new ArrayList<>();
        for (int a = 0; a < dianputu_imageServiceList.size(); a++) {
            list1.add(dianputu_imageServiceList.get(a).getPhotoPath());
        }
        mapjson.put("shopImgs", list1);


        String lifeCityCopartnerDTO = gson.toJson(mapjson);//map转json字符串
        minePersonPresenter.Update(lifeCityCopartnerDTO);
    }

    private String slipet(String list) {

        return StringUtils.strip(list.toString(), "[]");
    }

    private void TimerDialog(final int code) {
        String[] arreaArr = getActivity().getResources().getStringArray(R.array.timer_array);
        final List<String> shooting_type_list = Arrays.asList(arreaArr);
        new MenuDialog.Builder(this)
                .setCancel("取消") // 设置 null 表示不显示取消按钮
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setList(shooting_type_list)
                .setListener(new MenuDialog.OnListener() {

                    @Override
                    public void onSelected(Dialog dialog, int position, String text) {
                        switch (code) {
                            case 0:
                                seletTimer.setText(shooting_type_list.get(position).toString());
                                break;
                            case 1:
                                endTimer.setText(shooting_type_list.get(position).toString());
                                break;
                        }
                    }

                    @Override
                    public void onCancel(Dialog dialog) {
                        toast("取消了");
                    }
                })
                .setGravity(Gravity.BOTTOM)
                .setAnimStyle(BaseDialog.AnimStyle.BOTTOM)
                .show();
    }
}